package com.sskj.bibi.ui.fragment;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.mvc.MVCHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.bibi.R;
import com.sskj.bibi.R2;
import com.sskj.bibi.bean.EntrustBean;
import com.sskj.bibi.component.DaggerUserDataComponent;
import com.sskj.bibi.presenter.AllEntrustPresenter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.enums.ColorEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.PageDataSource;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * 全部委托
 */
@Route(path = RConfig.BIBI_All_ENTRUST)
public class AllEntrustFragment extends BaseFragment<AllEntrustPresenter> {


    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private SlimAdapter slimAdapter;
    private int curPos;
    private MaterialDialog cancelTip;
    private MVCHelper<List<EntrustBean>> mvcHelper;
    @Autowired
    String qu;
    @Inject
    UserViewModel userViewModel;
    UserData userData;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_all_entrust;
    }

    @Override
    protected AllEntrustPresenter getPresenter() {
        return new AllEntrustPresenter();
    }

    @Override
    protected void initView() {

        ARouter.getInstance().inject(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, data -> {
            if (data != null && data.size() > 0) {
                userData = data.get(0);
            } else {
                userData = null;
            }
        });

        SparseArray<String> state = new SparseArray<>();
        state.put(0, "（已触发）");
        state.put(1, "（已触发）");
        state.put(2, "（已触发）");
        state.put(4, "（未触发）");
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setLastDraw(false)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 20))
                .setPaintColor(ContextCompat.getColor(App.INSTANCE, R.color.libBg))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.bibi_recy_item_current_entrust, new SlimInjector<EntrustBean>() {
            @Override
            public void onInject(EntrustBean data, IViewInjector injector, List payloads) {
                injector.text(R.id.tvOrderType, data.isBuy() ? "买入" : "卖出")
                        .textColor(R.id.tvOrderType, ColorEnum.getColor(data.isBuy()))
                        .text(R.id.tvCoinType, data.getLCode() + "/" + data.getRCode())
                        .text(R.id.tvTime, data.getTime())
                        .text(R.id.tvDeal, "撤单")
                        .text(R.id.tvTitlePrice, String.format("委托价(%s)", data.getRCode()))
                        .text(R.id.tvTitleNum, data.isBuyAndMarket() ? "总金额" : String.format("委托量(%s)", data.getLCode()))
                        .text(R.id.tvTitleDealNum, String.format("实际成交(%s)", data.getLCode()))
                        .text(R.id.tvPrice, data.isMarket() ? "市价交易" : data.getPrice())
                        .text(R.id.tvNum, data.isBuyAndMarket() ? data.getTotalMoney() : CoinUtil.keepCoinNum(data.getLCode(), data.getNum()))
                        .text(R.id.tvcfj, String.format("触发价(%s)", data.getRCode()))
                        .text(R.id.tvcfjNum, data.getTouchPrice() + state.get(data.getState()))
                        .text(R.id.tvDealNum, data.getDealNum())
                        .clicked(R.id.tvDeal, (v) -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            if (userData.getLawWaring() == 2) {
                                EntrustBean dataItem = (EntrustBean) slimAdapter.getDataItem(curPos);
                                mPresenter.cancelEntrust(dataItem.getId(), dataItem.getTradeType() + "");
                            } else {
                                dealCancel();
                            }
                        });
                injector.findViewById(R.id.tvcfj).setVisibility(data.getBillPriceType() == 3 ? View.VISIBLE : View.GONE);
                injector.findViewById(R.id.tvcfjNum).setVisibility(data.getBillPriceType() == 3 ? View.VISIBLE : View.GONE);
            }
        }).attachTo(recyclerView);
        slimAdapter.updateData(new ArrayList());
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(new PageDataSource<>(this, coolRefreshView, (PageDataSource.OnLoadSource<EntrustBean>) page -> mPresenter.getEntrustList(page + "", "10", null, "2", null, userData)));
        mvcHelper.setAdapter(slimAdapter);
    }


    private void dealCancel() {
        if (cancelTip == null) {
            cancelTip = TipUtil.getSureTip(getActivity(), "撤销", () -> {
                EntrustBean dataItem = (EntrustBean) slimAdapter.getDataItem(curPos);
                mPresenter.cancelEntrust(dataItem.getId(), dataItem.getTradeType() + "");

            });
        }
        cancelTip.show();
    }

    @Override
    public void initData() {
        mvcHelper.refresh();
    }

    public void cancelReturn() {
        LiveDataBus.get().with(RxBusCode.BIBI_FRESH).postValue(1);
        mvcHelper.refresh();
    }
}
